package com.Gwo.org.service.impl;

import com.Gwo.basic.utils.PageList;
import com.Gwo.org.domain.Department;
import com.Gwo.org.mapper.DepartmentMapper;
import com.Gwo.org.query.DepartmentQuery;
import com.Gwo.org.service.IDeptService;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DeptServiceImpl implements IDeptService {
    @Autowired
    private DepartmentMapper deptMapper;

    @Override
    public Department findById(Long id) {
        return deptMapper.findById(id);
    }

    @Override
    public List<Department> findAll() {
        return deptMapper.findAll();
    }

    @Override
    @Transactional
    public void add(Department department) {
        deptMapper.add(department);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        deptMapper.delete(id);
    }

    @Override
    @Transactional
    public void update(Department department) {
        deptMapper.update(department);
    }

    @Override
    public PageList<Department> queryByPage(DepartmentQuery query) {
        if (!StringUtils.isEmpty(query.getKeyword())){
            query.setKeyword(query.getKeyword().trim());
        }
        // 查询数量
        Integer totals = deptMapper.queryByCount(query);
        // 查询数据
        List<Department> departments = deptMapper.queryByPage(query);
        if(departments.size()==0){
            return null;
        }
        return new PageList<Department>(totals,departments);
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        deptMapper.batchDelete(ids);
    }

    @Override
    public List<Department> getDeptTree() {
        List<Department> deptList = deptMapper.findAll();
        List<Department> result = new ArrayList<>();
        Map<Long, Department> collect = deptList.stream().collect(Collectors.toMap(e-> e.getId(), e -> e));
        for (Department d:deptList) {
            if(null != d.getParentId()){
                //说明它有父亲
                /*for (Department parent:deptList) {
                    if(d.getParentId().equals(parent.getId())){
                        parent.getChildren().add(d);
                        break;
                    }
                }*/
                Department parent = collect.get(d.getParentId());
                parent.getChildren().add(d);
            }else{
                result.add(d);
            }
        }
        return result;
    }
}
